// import { App } from 'antd'
import { getAppVoById, listAppChatHistory } from '@/apis'
import { ChatMessage } from '@/components'
import { UserOutlined } from '@ant-design/icons'
import { Sender } from '@ant-design/x'
import { message } from 'antd'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useNavigate, useParams, useSearchParams } from 'react-router'
import request from '@/apis/instance'
import { API_BASE_URL } from '@/config/env'
import { produce } from 'immer'
import 'highlight.js/styles/github-dark.css'
import './ChatMessage.css'

interface Message {
  type: 'user' | 'ai'
  content: string
  loading?: boolean
  createTime?: string
}
export const Chat = () => {
  const [messages, setMessages] = useState<Message[]>([])
  const [userInput, setUserInput] = useState('')
  const params = useParams()
  const [_, setAppInfo] = useState<API.AppVO>()
  const navigate = useNavigate()
  // const [historyLoaded, setHistoryLoaded] = useState(false)
  const historyLoadedRef = useRef(false)
  const [searchParams] = useSearchParams()
  const sendMessage = async () => {
    if (!userInput.trim()) return
    let mesTrim = userInput.trim()
    setMessages(
      produce((draft) => {
        draft?.push({ type: 'user', content: mesTrim })
      })
    )
    setUserInput('')
    await generateCode(mesTrim)
    message.success('发送成功')
  }
  const sendInitialMessage = async (prompt: string) => {
    setMessages(
      produce((draft) => {
        draft?.push({ type: 'user', content: prompt })
      })
    )
    await generateCode(prompt)
  }
  const loadChatHistory = useCallback(async () => {
    if (!params?.id || historyLoadedRef.current) return
    try {
      const body: API.listAppChatHistoryParams = {
        appId: params.id,
        pageSize: 10,
      }
      const res = await listAppChatHistory(body)
      if (res.data.code === 0 && res.data.data) {
        const chatHistories = res.data.data.records || []
        const historyMessages: Message[] = chatHistories
          .map((chat) => ({
            type: (chat.messageType === 'user' ? 'user' : 'ai') as 'user' | 'ai',
            content: chat.message || '',
            createTime: chat.createTime,
          }))
          .reverse() // 反转数组，让老消息在前
        setMessages(historyMessages)
        historyLoadedRef.current = true
      }
    } catch (error: any) {
      message.error('加载对话历史失败：', error)
    }
  }, [params?.id])

  const fetchAppInfo = useCallback(async () => {
    if (!params?.id || historyLoadedRef.current) return
    try {
      const res = await getAppVoById({ id: params?.id })
      if (res.data.code === 0 && res.data.data) {
        const appInfo = res.data.data
        setAppInfo(appInfo)
        await loadChatHistory()
        if (appInfo.initPrompt && messages?.length === 0 && historyLoadedRef.current) {
          await sendInitialMessage(appInfo.initPrompt)
        }
      } else {
        message.error('获取应用信息失败')
        navigate('/')
      }
    } catch (error: any) {
      message.error('获取应用信息失败：', error)
    }
  }, [params?.id])
  useEffect(() => {
    fetchAppInfo()
  }, [])

  const generateCode = async (message: string) => {
    let eventSource: EventSource | null = null
    let streamCompleted = false
    try {
      const baseURL = request.defaults.baseURL || API_BASE_URL
      const body = new URLSearchParams({
        appId: params?.id || '',
        message: message,
        roleType: searchParams.get('roleType') ?? '2',
      })
      setMessages(
        produce((draft) => {
          draft?.push({ type: 'ai', content: '', loading: true })
        })
      )
      const url = `${baseURL}/app/chat/gen/code?${body}`
      eventSource = new EventSource(url, {
        withCredentials: true,
      })
      let fullContent = ''
      eventSource.onmessage = (event) => {
        if (streamCompleted) return
        try {
          const parsed = JSON.parse(event.data)
          const content = parsed.d
          if (content !== undefined && content !== null) {
            if (content === '\n') fullContent += content + content
            else fullContent += content

            setMessages(
              produce((draft) => {
                if (draft && draft.length >= 0) {
                  draft[draft.length - 1].content = fullContent
                  draft[draft.length - 1].loading = false
                }
              })
            )
          }
        } catch (error) {
          console.error('解析消息失败：', error)
        }
      }
      eventSource.addEventListener('done', function () {
        if (streamCompleted) return
        streamCompleted = true
        eventSource?.close()
      })
    } catch (error) {
      console.error('创建 EventSource 失败：', error)
    }
  }

  return (
    <div key={params?.id} className="h-screen w-full relative min-w-0">
      <div className="relative h-full flex-1 flex overflow-x-hidden overflow-y-scroll pt-6 box-border">
        <div className="relative mx-auto flex h-full w-full max-w-3xl flex-1 flex-col md:px-2">
          <div className="flex-1 flex flex-col gap-3 px-4 max-w-3xl mx-auto w-full pt-1">
            <>
              {messages?.map((message, index) => {
                return (
                  <ChatMessage
                    message={message.content}
                    key={index}
                    placement={message.type === 'user' ? 'right' : 'left'}
                    avatar={<UserOutlined />}
                    loading={message.loading}
                  />
                )
              })}
            </>
          </div>
          <div className="sticky bottom-[10px] mx-auto w-full pt-6 z-[5]">
            <Sender onSubmit={sendMessage} allowSpeech value={userInput} onChange={setUserInput} />
          </div>
        </div>
      </div>
    </div>
  )
}
